<template>
  <div>
    <div
      style="height: 60px; background-color: #fff; display: flex; align-items: center; border-bottom: 1px solid #ddd">
      <div style="flex: 1">
        <div style="padding-left: 20px; display: flex; align-items: center">
          <img src="@/assets/imgs/OIP-C.jpg" alt="" style="width: 40px">
          <div style="font-weight: bold; font-size: 24px; margin-left: 5px">团队小助手</div>
        </div>
      </div>
      <div style="width: fit-content; padding-right: 10px; display: flex; align-items: center;">
        <el-badge :value="unreadNotifications" :max="99" :hidden="unreadNotifications === 0" class="notification-badge">
          <el-popover placement="bottom" :width="300" trigger="click" @show="markNotificationsAsRead">
            <template #reference>
              <el-button circle>
                <el-icon>
                  <Bell />
                </el-icon>
              </el-button>
            </template>
            <div class="notification-container">
              <div class="notification-header">
                <span>通知</span>
                <el-button type="text" size="small" @click="clearNotifications">清空</el-button>
              </div>
              <div v-if="notifications.length === 0" class="empty-notification">
                <el-icon>
                  <InfoFilled />
                </el-icon>
                <span>暂无通知</span>
              </div>
              <div v-else class="notification-list">
                <div v-for="(notification, index) in notifications" :key="index" class="notification-item">
                  <el-icon>
                    <SuccessFilled />
                  </el-icon>
                  <div class="notification-content">
                    <div class="notification-title">{{ notification.title }}</div>
                    <div v-if="notification.description" class="notification-description">{{ notification.description }}
                    </div>
                    <div v-if="notification.updatedFields" class="notification-updated-fields">
                      <span>更新内容：</span>
                      <el-tag v-for="field in notification.updatedFields.split('、')" :key="field" size="small"
                        type="warning" style="margin-right: 5px; margin-bottom: 5px">{{ field }}</el-tag>
                    </div>
                    <div v-if="notification.taskId" class="notification-details">
                      <el-tag size="small" type="info">#{{ notification.taskId }}</el-tag>
                      <el-tag v-if="notification.status" size="small" type="success" style="margin-left: 5px">{{
                        notification.status
                          === 'completed' ? '已完成' : notification.status }}</el-tag>
                      <span v-if="notification.completedBy" class="completed-by">由 <strong>{{ notification.completedBy
                          }}</strong>
                        完成</span>
                    </div>
                    <div class="notification-time">{{ formatTime(notification.time) }}</div>
                  </div>
                </div>
              </div>
            </div>
          </el-popover>
        </el-badge>
        <span style="margin-left: 10px;">{{ data.user.username || data.user.name || '用户' }}</span>
      </div>
    </div>

    <div style="display: flex">
      <div
        :style="{ width: isCollapse ? '64px' : '200px', borderRight: '1px solid #ddd', minHeight: 'calc(100vh - 60px)', transition: 'width 0.3s' }">
        <el-menu router style="border: none" :default-active="router.currentRoute.value.path"
          :default-openeds="['/home', '2']" :collapse="isCollapse">
          <el-menu-item index="/home">
            <el-icon>
              <House />
            </el-icon>
            <span>系统首页</span>
          </el-menu-item>
          <el-menu-item index="/projects">
            <el-icon>
              <Folder />
            </el-icon>
            <span>项目管理</span>
          </el-menu-item>
          <el-menu-item index="/knowledge">
            <el-icon>
              <Document />
            </el-icon>
            <span>知识管理</span>
          </el-menu-item>
          <el-menu-item index="/group">
            <el-icon>
              <UserFilled />
            </el-icon>
            <span>小组管理</span>
          </el-menu-item>
          <el-menu-item index="/person">
            <el-icon>
              <User />
            </el-icon>
            <span>个人资料</span>
          </el-menu-item>
          <el-menu-item index="/password">
            <el-icon>
              <Lock />
            </el-icon>
            <span>修改密码</span>
          </el-menu-item>
          <el-menu-item index="login" @click="logout">
            <el-icon>
              <SwitchButton />
            </el-icon>
            <span>退出系统</span>
          </el-menu-item>
        </el-menu>

        <!-- 收起栏 -->
        <div class="collapse-btn" @click="toggleCollapse" :title="isCollapse ? '展开' : '收起'">
          <el-tooltip :content="isCollapse ? '展开' : '收起'" placement="top" :show-after="300">
            <el-icon>
              <component :is="isCollapse ? 'Expand' : 'Fold'" />
            </el-icon>
          </el-tooltip>
        </div>
      </div>

      <div style="flex: 1; width: 0; background-color: #f8f8ff; padding: 10px">
        <router-view @updateUser="updateUser" />
      </div>
    </div>

  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted, getCurrentInstance } from "vue";
import router from "@/router";
import { ElMessage } from "element-plus";
import { Fold, Expand } from '@element-plus/icons-vue';

// 添加收起状态控制
const isCollapse = ref(false);

// 切换收起/展开状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
};
import { House, Folder, Document, User, Lock, SwitchButton } from "@element-plus/icons-vue";

// 获取全局事件总线
const { proxy } = getCurrentInstance();
const emitter = proxy.emitter;

// 通知相关数据
const notifications = ref([]);
const unreadNotifications = ref(0);

// 添加通知
const addNotification = (data) => {
  // 如果传入的是字符串，则创建简单通知
  const notification = typeof data === 'string'
    ? {
      title: data,
      time: new Date(),
      read: false
    }
    : {
      title: data.title || '新通知',
      description: data.description || '',
      taskId: data.id || '',
      status: data.status || '',
      completedBy: data.completedBy || '',  // 添加完成人信息
      updatedFields: data.updatedFields || '', // 添加更新的字段信息
      time: new Date(),
      read: false
    };
  notifications.value.unshift(notification);
  unreadNotifications.value++;

  // 同时显示弹出通知
  ElNotification({
    title: typeof data === 'string' ? '系统通知' : '任务更新通知',
    message: typeof data === 'string'
      ? data
      : data.description || `${data.title}${data.completedBy ? ` (由 ${data.completedBy} 完成)` : ''}`,
    type: 'success',
    duration: 5000
  });

  // 保存到本地存储
  saveNotifications();
};

// 标记所有通知为已读
const markNotificationsAsRead = () => {
  if (unreadNotifications.value > 0) {
    notifications.value.forEach(notification => {
      notification.read = true;
    });
    unreadNotifications.value = 0;
    saveNotifications();
  }
};

// 清空所有通知
const clearNotifications = () => {
  notifications.value = [];
  unreadNotifications.value = 0;
  localStorage.removeItem('notifications');
};

// 保存通知到本地存储
const saveNotifications = () => {
  localStorage.setItem('notifications', JSON.stringify(notifications.value));
};

// 从本地存储加载通知
const loadNotifications = () => {
  try {
    const savedNotifications = JSON.parse(localStorage.getItem('notifications') || '[]');
    notifications.value = savedNotifications;
    unreadNotifications.value = savedNotifications.filter(n => !n.read).length;
  } catch (error) {
    console.error('加载通知失败:', error);
  }
};

// 格式化时间
const formatTime = (time) => {
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取当前用户信息
const getCurrentUser = () => {
  try {
    return JSON.parse(localStorage.getItem('system-user') || '{}');
  } catch (error) {
    console.error('获取当前用户信息失败:', error);
    return {};
  }
};

// 任务更新事件处理函数
const handleTaskStatusChange = async (data) => {
  // 获取当前用户信息
  const currentUser = data.user || getCurrentUser();
  const username = currentUser?.username || currentUser?.name || '';

  // 使用新的通知格式，传递完整的任务数据
  // 从描述中提取更新的字段
  const updatedFields = data.description.includes('已更新：')
    ? data.description.split('已更新：')[1]
    : '';

  addNotification({
    title: `任务 "${data.title}" 已更新`,
    description: data.description,
    id: data.id,
    status: data.status,
    completedBy: data.completedBy || '', // 添加完成人信息
    updatedFields: updatedFields // 添加更新的字段信息
  });

  // 如果当前用户是小组负责人，获取小组成员并通知他们
  if (username) {
    try {
      // 获取当前用户所在小组的成员
      const response = await request.get('/api/members/byLeader', {
        params: { leader: username }
      });

      if (response.code === '200' && response.data) {
        const groupMembers = response.data;
        console.log('通知同组成员:', groupMembers);

        // 如果当前用户不是小组负责人，可能需要另一种方式获取同组成员
        // 这里可以通过WebSocket或其他方式通知同组成员
      }
    } catch (error) {
      // 记录错误信息到控制台（非错误级别）
      console.info({
        message: '获取小组成员错误',
        error: error.message,
        timestamp: new Date().toISOString(),
        type: 'group_members_error'
      });

      // 处理不同类型的错误
      if (error.response) {
        // 服务器响应错误
        const status = error.response.status;
        const data = error.response.data;
        
        switch (status) {
          case 400:
            console.info('请求参数错误:', data.msg);
            break;
          case 401:
            console.info('身份验证失败，需要重新登录');
            break;
          case 403:
            console.info('权限不足，无法获取小组成员信息');
            break;
          case 404:
            console.info('未找到相关小组信息');
            break;
          case 500:
            console.info('服务器内部错误');
            break;
          case 503:
            console.info('服务暂时不可用');
            break;
          default:
            console.info(`获取小组成员失败 (错误代码: ${status}):`, data.msg);
        }
      } else if (error.request) {
        // 网络错误
        if (error.code === 'ECONNABORTED') {
          console.info('请求超时，网络连接可能存在问题');
        } else if (error.message.includes('Network Error')) {
          console.info('网络连接失败');
        } else {
          console.info('网络请求失败');
        }
      } else {
        // 其他错误
        console.info('获取小组成员时发生未知错误');
      }
    }
  }
};

// 组件挂载时
onMounted(() => {
  // 加载保存的通知
  loadNotifications();

  // 监听任务状态变更事件
  emitter.on('task-status-change', handleTaskStatusChange);
});

// 组件卸载时
onUnmounted(() => {
  // 移除事件监听
  emitter.off('task-status-change', handleTaskStatusChange);
});

const data = reactive({
  user: (() => {
    try {
      return JSON.parse(localStorage.getItem('system-user') || '{}');
    } catch (error) {
      console.error('JSON解析失败:', error);
      ElMessage.error('数据解析失败，请联系管理员');
      return {};
    }
  })()
})

if (data.user?.phone) {  // 改为检查具体登录标识
  // 用户已登录，正常加载页面
} else {
  ElMessage.error('请登录！')
  router.push('/login')
}

// 当用户信息更新时，重新获取用户数据
const updateUser = () => {
  // 从localStorage获取最新的用户信息
  try {
    const userData = localStorage.getItem('system-user');
    if (userData) {
      data.user = JSON.parse(userData);
    }
  } catch (error) {
    console.error('JSON解析失败:', error);
  }
  try {
    data.user = JSON.parse(localStorage.getItem('system-user') || '{}');
  } catch (error) {
    console.error('JSON解析失败:', error);
    ElMessage.error('数据解析失败，请联系管理员');
    data.user = {};
  }
}

const logout = () => {
  ElMessage.success('退出成功')
  localStorage.removeItem('system-user')
  router.push('/login')
}
</script>

<style scoped>
.el-menu-item.is-active {
  background-color: #e0edfd !important;
}

.el-menu-item:hover {
  color: #1967e3;
}

:deep(th) {
  color: #333;
}

/* 收起按钮样式 */
.collapse-btn {
  position: absolute;
  bottom: 20px;
  left: 20px;
  /* 从居中改为左对齐 */
  width: 32px;
  height: 32px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f2f6fc;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
  transition: all 0.3s;
}

/* 通知样式 */
.notification-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.notification-content {
  margin-left: 10px;
  flex: 1;
}

.notification-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.notification-description {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
  white-space: pre-wrap;
  word-break: break-word;
}

.notification-updated-fields {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin: 5px 0;
  font-size: 12px;
}

.notification-updated-fields span {
  margin-right: 5px;
  color: #666;
}

.notification-details {
  margin-top: 5px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 5px;
}

.completed-by {
  font-size: 12px;
  color: #606266;
  margin-left: 5px;
  background-color: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.collapse-btn:hover {
  background-color: #e0edfd;
  color: #1967e3;
}
</style>
